# -*- coding: utf-8 -*-
# run.py
"""
应用启动脚本 🎬

便捷的应用启动入口
"""

import os
import sys
import click
import uvicorn
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

from backend.core.config import get_app_settings
from backend.utils.uvicorn_config import get_uvicorn_log_config


@click.group()
def cli():
    """AI Code Assistant 启动工具 🚀
    
    这是一个命令行工具，用于管理和运行 CodeBuddy Craft 应用。
    使用 --help 选项查看可用命令。
    """
    # 检查Python版本
    import platform
    python_version = platform.python_version()
    min_version = "3.10.0"
    
    if python_version < min_version:
        click.echo(f"❌ Python版本过低: {python_version}")
        click.echo(f"💡 请使用 Python {min_version} 或更高版本")
        sys.exit(1)
    
    # 检查环境变量
    env_file = Path(".env")
    if not env_file.exists():
        click.echo("⚠️ 未找到 .env 文件，将使用默认配置")
    
    # 显示应用信息
    try:
        settings = get_app_settings()
        if settings.is_development:
            click.echo(f"🛠️  开发模式: {settings.PROJECT_NAME} v{settings.PROJECT_VERSION}")
    except Exception:
        # 如果配置加载失败，不阻止命令执行
        pass


@cli.command()
@click.option("--host", default=None, help="服务器主机地址")
@click.option("--port", type=int, default=None, help="服务器端口")
@click.option("--reload", is_flag=True, help="启用自动重载")
@click.option("--workers", type=int, default=None, help="工作进程数")
@click.option("--log-level", default=None, help="日志级别")
def serve(host, port, reload, workers, log_level):
    """启动服务器 🌟"""

    settings = get_app_settings()

    # 使用命令行参数覆盖配置
    server_host = host or settings.HOST
    server_port = port or settings.PORT
    server_reload = reload or (settings.RELOAD and settings.is_development)
    server_workers = workers or (settings.WORKERS if settings.is_production else 1)
    server_log_level = log_level or settings.LOG_LEVEL

    click.echo(f"🚀 启动 {settings.PROJECT_NAME} v{settings.PROJECT_VERSION}")
    click.echo(f"📍 环境: {settings.ENVIRONMENT}")
    click.echo(f"🌐 地址: http://{server_host}:{server_port}")

    if settings.is_development:
        click.echo(f"📚 API文档: http://{server_host}:{server_port}/docs")

    try:
        uvicorn.run(
            "main:app",
            host=server_host,
            port=server_port,
            reload=server_reload,
            workers=server_workers if not server_reload else 1,
            log_level=server_log_level.lower(),
            access_log=True,
            log_config=get_uvicorn_log_config(),
        )
    except KeyboardInterrupt:
        click.echo("\n👋 服务器已停止")
    except Exception as e:
        click.echo(f"❌ 启动失败: {e}")
        sys.exit(1)


@cli.command()
def init():
    """初始化应用 🔧"""
    import asyncio
    from backend.database.connection import init_db

    click.echo("🔧 正在初始化应用...")

    try:
        # 初始化数据库
        asyncio.run(init_db())
        click.echo("✅ 数据库初始化完成")

        # 创建必要目录
        from backend.core.config import create_directories
        settings = get_app_settings()
        create_directories(settings)
        click.echo("📁 目录创建完成")

        click.echo("🎉 应用初始化完成！")

    except Exception as e:
        click.echo(f"❌ 初始化失败: {e}")
        sys.exit(1)


@cli.command()
def check():
    """检查系统状态 🏥"""
    import asyncio
    from backend.database.connection import health_check

    click.echo("🏥 检查系统状态...")

    try:
        settings = get_app_settings()

        # 配置检查
        click.echo("📋 配置检查:")
        click.echo(f"  - 环境: {settings.ENVIRONMENT} ✅")
        click.echo(
            f"  - 数据库: {settings.DATABASE_URL.split('@')[-1] if '@' in settings.DATABASE_URL else 'SQLite'} ✅")

        # 数据库连接检查
        click.echo("🗄️ 数据库检查:")
        db_health = asyncio.run(health_check())

        if db_health["status"] == "healthy":
            click.echo(f"  - 连接状态: {db_health['status']} ✅")
            click.echo(f"  - 响应时间: {db_health['response_time_ms']}ms")
        else:
            click.echo(f"  - 连接状态: {db_health['status']} ❌")
            click.echo(f"  - 错误: {db_health.get('error', '未知')}")

        # 文件系统检查
        click.echo("📁 文件系统检查:")
        if settings.LOG_FILE:
            log_dir = Path(settings.LOG_FILE).parent
            if log_dir.exists():
                click.echo(f"  - 日志目录: {log_dir} ✅")
            else:
                click.echo(f"  - 日志目录: {log_dir} ❌")

        upload_dir = Path(settings.UPLOAD_DIR)
        if upload_dir.exists():
            click.echo(f"  - 上传目录: {upload_dir} ✅")
        else:
            click.echo(f"  - 上传目录: {upload_dir} ❌")

        click.echo("🎉 系统检查完成！")

    except Exception as e:
        click.echo(f"❌ 检查失败: {e}")
        sys.exit(1)


if __name__ == "__main__":
    # cli()
    # init()
    # check()
    serve()
